<!--
 * @Author: liaoxing
 * @Date: 2022-02-16 16:48:55
 * @LastEditors: liaoxing
 * @LastEditTime: 2022-03-10 09:28:25
 * @Description: liaoxing created
 * @FilePath: \pin-xin-admin\src\views\business\reportcenter\category.vue
-->
<template>
  <div class="category">
    <header class="flex-align-center relative">
      <el-form
        :inline="true"
        :model="searchValue"
        class="demo-form-inline"
        size="mini"
      >
        <el-form-item label="报表名称">
          <el-input v-model="searchValue.name"></el-input>
        </el-form-item>
        <el-form-item label="创建人">
          <el-input v-model="searchValue.create_by"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getReportList">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button class="absolute" style="right: 16px" size="mini" type="primary" @click="addReport">新建报表</el-button>
    </header>
    <main>
      <el-table
        :header-cell-style="{ backgroundColor: '#F2F6FC' }"
        :data="reportList"
        style="width: 100%"
      >
        <el-table-column label="序号" type="index" align="center" width="100">
        </el-table-column>

        <el-table-column
          v-for="item in tableRenderList"
          align="center"
          :key="item.key"
          :prop="item.key"
          :label="item.label"
          :width="item.width || 'auto'"
        >
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <span
              class="jstarfont jstar-yanjing finger"
              @click="preview(scope.row.id)"
            ></span>
            <span style="margin-left: 10px" class="finger"
              ><i
                class="el-icon-edit-outline"
                @click.stop.prevent="openNewWindow(scope.row.id)"
              ></i
            ></span>
            <el-tooltip content="配置到菜单" placement="top" effect="dark">
              <span
                style="margin-left: 10px"
                class="jstarfont jstar-fenxiang finger"
                @click="handleAdd(scope.row)"
              ></span>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="float: right; margin-top: 20px"
        :current-page.sync="pn"
        :page-size="ps"
        layout="total, prev, pager, next, jumper"
        :total="totalSize"
      ></el-pagination>
    </main>

    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <treeselect
                v-model="form.parentId"
                :options="menuOptions"
                :normalizer="normalizer"
                :show-count="true"
                @select="selectMenu"
                placeholder="选择上级菜单"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType">
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="form.menuType != 'F'" label="菜单图标">
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input
                  slot="reference"
                  v-model="form.icon"
                  placeholder="点击选择图标"
                  readonly
                >
                  <svg-icon
                    v-if="form.icon"
                    slot="prefix"
                    :icon-class="form.icon"
                    class="el-input__icon"
                    style="height: 32px; width: 16px"
                  />
                  <i
                    v-else
                    slot="prefix"
                    class="el-icon-search el-input__icon"
                  />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sortOrder">
              <el-input-number
                v-model="form.sortOrder"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'F'" prop="path">
              <span slot="label">
                <el-tooltip
                  content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                路由地址
              </span>
              <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType == 'C'">
            <el-form-item prop="component">
              <span slot="label">
                <el-tooltip
                  content="访问的组件路径，如：`system/user/index`，默认在`views`目录下"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                组件路径
              </span>
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType == 'C'">
              <el-input
                v-model="form.query"
                placeholder="请输入路由参数"
                maxlength="255"
              />
              <span slot="label">
                <el-tooltip
                  content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`'
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                路由参数
              </span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import report from "@/api/report/newApi";
import {
  listMenu,
  addMenu,
} from "@/api/system/menu";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import store from '@/store'
import router from '@/router'
import RouterBase from 'vue-router'
export default {
  name: "category",
  components: { Treeselect, IconSelect },
  data() {
    return {
      searchValue: {
        name: "",
        create_by: "",
      },
      tableRenderList: [
        { label: "报表名称", key: "name" },
        { label: "创建人", key: "create_by" },
        { label: "创建时间", key: "create_time" },
        { label: "查看次数", key: "view_count" },
        // {label: "审核人", key: "key5"},
        // {label: "是否有报价", key: "key6"},
        // {label: "审核日期", key: "key7"}
      ],
      reportList: [],
      pn: 1,
      ps: 10,
      totalSize: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        menuName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" },
        ],
        sortOrder: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" },
        ],
        path: [
          { required: true, message: "路由地址不能为空", trigger: "blur" },
        ],
      },
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      currentItem: null,
      addUrl: "/jmreport/index/",
      currentCategoryId: "1499191406656937985"
    };
  },
  watch: {
    pn: {
      deep: true,
      handler() {
        this.getReportList();
      },
    },
    'form.parentId': {
      deep: true,
      handler (value) {
        console.log(value)
      }
    }
  },
  created() {
    this.getReportList();
  },
  methods: {
    /* 新建报表 */
    addReport () {
      this.$report.addReport()
        .then(res => {
          window.open(window.repoortURL + this.addUrl + res.result.id + "?tpye=" + this.currentCategoryId)
        })
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.menuName,
        children: node.children,
        path: node.path
      };
    },
    /* 选择菜单 */
    selectMenu (node) {
      this.form.parentId = node.id
    },
    // 选择图标
    selected(name) {
      this.form.icon = name;
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listMenu({ ps: 9999, pn: 1 }).then((response) => {
        this.menuOptions = [];
        const menu = { id: 0, menuName: "主类目", children: [] };
        menu.children = this.handleTree(response.data.rows, "id");
        this.menuOptions.push(menu);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset(item) {
      this.currentItem = null
      this.form = {
        parentId: 0,
        menuName: item ? item.name : '',
        icon: undefined,
        menuType: "C",
        sortOrder: undefined,
        isFrame: "1",
        isCache: "0",
        visible: 0,
        status: 1,
        component: "myreport/index",
        path: "index/" + (item ? (item.id || '') : '')
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd(item) {
      this.reset(item);
      this.currentItem = item
      this.getTreeselect();
      this.form.parentId = "1497090110752198657";
      this.open = true;
      this.title = "配置报表到左侧菜单";
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          addMenu(this.form).then(() => {
            this.$modal.msgSuccess("添加成功, 请重新刷新页面查看菜单");
            this.open = false;

            store.dispatch('GenerateRoutes').then(async (accessRoutes) => {
              // await this.clearRouters(accessRoutes)
              // console.log(router)
              // router.addRoutes(accessRoutes)
            })
          });
        }
      })
    },
    /* 清除路由再加 */
    clearRouters (accessRoutes) {
      return new Promise(res => {
        router.matcher = new RouterBase({
          routes: accessRoutes
        }).matcher
        res()
      })
    },
    openNewWindow(id) {
      window.open(window.repoortURL + "/jmreport/index/" + id, "_blank");
    },
    getReportList() {
      let params = {
        pn: this.pn,
        ps: this.ps,
      };

      if (this.searchValue.name) {
        params["name_like"] = this.searchValue.name;
      }

      if (this.searchValue.create_by) {
        params["create_by_like"] = this.searchValue.create_by;
      }

      report
        .queryReport(params)
        .then((res) => {
          if (res.code === 200) {
            this.reportList = res.data.rows;
            this.totalSize = res.data.total * 1;
          } else {
            this.$message.error(res.code + "-" + res.msg);
          }
        })
        .catch((e) => {
          this.$message.error(e.toString());
        });
    },
    resetSearch() {
      this.pn = 1;
      this.searchValue.name = "";
      this.searchValue.create_by = "";
      this.getReportList();
    },
    preview(id) {
      this.$router.push({
        path: "/business/reportcenter/report/viewreport",
        query: { id: id },
      });
    },
  },
};
</script>

<style lang="less">
.category {
  width: 100%;
  height: calc(100vh - 84px);
  box-sizing: border-box;
  padding: 16px;
  position: relative;
  background-color: #f3f5fa;
  header {
    height: 50px;
    padding: 0 16px;
    background-color: white;
    .el-form-item--mini.el-form-item {
      margin-bottom: 0;
      margin-left: 16px;
    }
  }
  main {
    margin-top: 16px;
    background-color: white;
    height: calc(100% - 66px);
    box-sizing: border-box;
    padding: 16px;
  }
}
</style>